package com.disdr.datacenter;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class TranslationExample {
    public static void main(String[] args) throws IOException {
        Map<String, String> phpToJava = new HashMap<String, String>();
        phpToJava.put("PHP", "Java");
        phpToJava.put("echo", "System.out.println");
        phpToJava.put("print", "System.out.print");
        phpToJava.put("var_dump", "System.out.println");
        phpToJava.put("print_r", "System.out.println");
        phpToJava.put("require", "import");
        phpToJava.put("include", "import");

        //String phpCode = "require 'example.php';";
        String phpCode = fileToString2("D:\\ideaSpace\\datacenter\\application\\ucenter\\controller\\User.php");
        String javaCode = translate(phpCode, phpToJava);

        System.out.println(javaCode);
    }

    public static String translate(String phpCode, Map<String, String> phpToJava) {
        String[] phpLines = phpCode.split("\\r?\\n");
        StringBuilder javaCodeBuilder = new StringBuilder();

        for (String phpLine : phpLines) {
            String[] phpStatement = phpLine.trim().split(" ");
            String phpKeyword = phpStatement[0];
            String javaKeyword = phpToJava.get(phpKeyword);

            if (javaKeyword != null) {
                phpLine = phpLine.replaceFirst(phpKeyword, javaKeyword);
            }

            javaCodeBuilder.append(phpLine).append("\n");
        }

        return javaCodeBuilder.toString();
    }
    public static String fileToString2(String path) throws IOException {
        FileReader reader = new FileReader(new File(path));
        StringBuilder stringBuilder = new StringBuilder();
        char[] buffer = new char[10];
        int size;
        while ((size = reader.read(buffer)) != -1) {
            stringBuilder.append(buffer, 0, size);
        }
        return stringBuilder.toString();
    }

}
